<template>
  <!-- 申报策略 表单 -->
  <a-modal
    v-model:open="visible"
    title="新增申报策略"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="650"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
      :disabled="props.isInfo"
    >
      <a-form-item label="执行日期" name="executionDate">
        <a-date-picker
          v-model:value="form.executionDate"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          class="formInput"
        />
      </a-form-item>
      <a-form-item label="模式" name="mode">
        <a-select
          ref="select"
          v-model:value="form.mode"
          class="formInput"
          placeholder="请选择模式"
          show-search
          optionFilterProp="label"
          @search="debouncedSearch"
        >
          <a-select-option :value="0">削峰</a-select-option>
          <a-select-option :value="1">填谷</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="户号" name="customerId">
        <a-select
          ref="select"
          v-model:value="form.customerId"
          class="formInput"
          placeholder="请输入搜索"
          show-search
          :filter-option="false"
          optionFilterProp="label"
          @search="debounceSearchCustomerManage"
        >
          <a-select-option v-for="item in customerNumList" :key="item.id">
            <span class="searchName">
              {{ item.companyName }}
              <p style="float: right">{{ item.num }}</p>
            </span>
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="执行时段" name="executionPeriod">
        <TimeRangeSelector
          v-model="form.executionPeriod"
          :disabled="props.isInfo"
          type="time"
          @change="() => formRef.validateFields(['executionPeriod'])"
        />
      </a-form-item>
      <a-form-item label="曲线计算日期" name="curveCalculationDate">
        <TimeRangeSelector
          v-model="form.curveCalculationDate"
          :disabled="props.isInfo"
          type="date"
          button-text="新增日期"
          @change="() => formRef.validateFields(['curveCalculationDate'])"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>

  <a-modal
    v-model:open="tipsVisible"
    title="提示"
    @ok="handleOk"
    class="addStation"
    :width="550"
    centered
  >
    <div>
      <InfoCircleOutlined style="color: orange" />
      暂未导入XXX日期的基线/用户电量数据，请调整曲线计算日期，或上传XX日期基线/用户电量数据后再进行新增。
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="tipsVisible = false"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import TimeRangeSelector from "@/views/conpoments/TimeRangeSelector.vue"
import { HOUR_LIST, HALF_HOUR_LIST } from "@/constants/dispatchCenter"
import { isArray, isObject, debounce } from "lodash-es"
const $api = inject("$api")
const props = defineProps({
  addRuleVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
  isInfo: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  provList: {
    type: Array,
  },
})
const loading = ref(false)
const visible = ref(props.addRuleVisible)
const tipsVisible = ref(false)
const emits = defineEmits(["update:addRuleVisible", "getDeclareList"])
watch(
  () => props.addRuleVisible,
  (val) => {
    visible.value = val
    if (val) {
      changeDateRange(form.value.timeQuantum) // 初始化时段
      if (props.isInfo) {
        form.value = {
          ...props.rowData,
        }
        changeDateRange(form.value.timeQuantum) // 有默认数据时，再根据时段选择时间范围重置时段list
        // 定义时间范围映射
        const timeRangeMappings = [
          { key: "superPeakTimeRange", type: "jian" },
          { key: "peakTimeRange", type: "feng" },
          { key: "flatTimeRange", type: "ping" },
          { key: "valleyTimeRange", type: "gu" },
          { key: "deepValleyTimeRange", type: "shengu" },
        ]
        // 处理每个时间范围字段
        timeRangeMappings.forEach((mapping) => {
          const ranges = props.rowData[mapping.key].split(",").filter(Boolean)
          ranges.forEach((range) => {
            const normalizedRange = range.trim()
            const hourObject = hourList.value.find(
              (hour) => hour.value === normalizedRange
            )
            if (hourObject) {
              hourObject.type = mapping.type // 设置对应的类型，即对应的颜色
            }
          })
        })
      }
      handleSearchCustomerManage("")
    }
  }
)
const hourList = ref([])
const labelCol = { style: { width: "110px" } }
const formRef = ref(null)
const date = ref()
const showDate = ref(false)
const form = ref({
  executionDate: null,
  mode: null,
  customerId: null,
  executionPeriod: [],
  curveCalculationDate: [],
})
const rules = ref({
  executionDate: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  mode: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
  customerNumber: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
  customerId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  executionPeriod: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value) => {
        if (form.value.executionPeriod.length === 0) {
          return Promise.reject("请选择执行时段")
        } else {
          return Promise.resolve()
        }
      },
    },
  ],
  curveCalculationDate: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value) => {
        if (form.value.curveCalculationDate.length === 0) {
          return Promise.reject("请选择曲线计算日期")
        } else {
          return Promise.resolve()
        }
      },
    },
  ],
})

const cancel = () => {
  emits("update:addRuleVisible", false)
  form.value = {
    executionDate: null,
    mode: null,
    customerId: null,
    executionPeriod: [],
    curveCalculationDate: [],
  }
  formRef.value.clearValidate()
}
const handleSaveDate = () => {
  if (date.value?.length > 0) {
    form.value.curveCalculationDate.push(date.value)
    showDate.value = false
    showDate.value = false
    date.value = []
    formRef.value.validateFields("curveCalculationDate")
  }
}
const prefixDate = (value) => {
  if (isArray(value)) {
    let date1 = value[0]
    let date2 = value[1]
    return date1 + "~" + date2
  }
  if (isObject(value)) {
    let date1 = value.startTime
    let date2 = value.endTime
    return date1 + "~" + date2
  }
}
const handleCloseDate = (index, type) => {
  switch (type) {
    case "executionPeriod":
      form.value.executionPeriod.splice(index, 1)
      break
    case "curveCalculationDate":
      form.value.curveCalculationDate.splice(index, 1)
      break
    default:
      break
  }
}
const changeDateRange = (value) => {
  if (value === 1) {
    hourList.value = HOUR_LIST.map((item) => {
      return {
        value: item,
        type: "",
      }
    })
  } else {
    hourList.value = HALF_HOUR_LIST.map((item) => {
      return {
        value: item,
        type: "",
      }
    })
  }
}
const handleSearch = async (value) => {
  const res = await $api.modelParamList({
    name: value,
  })
  searchList.value = res.data.map((item) => {
    return {
      ...item,
      label: item.name,
      value: item.id,
    }
  })
}
const debouncedSearch = debounce(handleSearch, 300)
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const params = {
        ...form.value,
        executionPeriod: form.value.executionPeriod.map((item) => {
          return item.join("~")
        }),
        curveCalculationDate: form.value.curveCalculationDate.map((item) => {
          return item.join("~")
        }),
        customerNumber: customerNumList.value.find(
          (item) => item.id === form.value.customerId
        )?.num,
      }
      loading.value = true
      const res = await $api.applyStrategy(params)
      loading.value = false
      if (res.code === 0) {
        message.success("新增成功")
        emits("getDeclareList")
        cancel()
      }
    })
    .catch((error) => {
      console.log("error", error)
    })
}
const customerNumList = ref([])
const handleSearchCustomerManage = async (value) => {
  const res = await $api.elecAccManagePage({
    projectName: value,
    size: 99,
    current: 1,
  })
  if (res.code === 0) {
    customerNumList.value = res.data.records
  }
}
const debounceSearchCustomerManage = debounce(handleSearchCustomerManage, 300)
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 460px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.addDate {
  margin-top: 10px;
}
.handleSaveDate {
  margin-left: 10px;
  font-size: 16px;
}
.tagConent {
  width: 390px;
}
.ant-tag {
  margin-top: 10px;
  display: inline-block;
}
</style>
